package com.ifcar.app.activity;

import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import com.ifcar.app.db.DBUtils;
import com.ifcar.app.download.AppUpdateService;
import com.ifcar.app.util.Constant;
import com.ifcar.app.util.HttpUtils;
import com.ifcar.app.util.Logger;
import com.ifcar.app.util.PicUtil;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.Tools;
import com.ifcar.app.util.VersionCompat;
import com.ifcar.app.activity.R;

/**
 * 主界面加载
 * 
 * @author xali
 * 
 */
public class Splash extends BaseActivity {

	private final int UPDATE = 1;
	private final int NOTICE = UPDATE + 1;
	private final int NORMAL = NOTICE + 1;
	private final int COVER = NORMAL + 1;
	private final int STOP = COVER + 1;
	private final String UPDATETYPE = "update";
	private SharedPreferences sp;
	private String title, message, version, type;
	private JSONArray custom_default;
	private int delaymillios = 5;
	private String currentdate = "";

	private String cover_src = "";
	private String cover_start = "";
	private String cover_end = "";
	public String FORCE_GUIDE_NAME = "forceguide";
	public String FORCE_TEXTSIZE_NAME = "forcetextsize";
	private boolean iscancle = false;
	private ViewStub viewstub_ad;
	private WebView mWebView;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			iscancle = true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.main_index);
		
		mWebView = (WebView) findViewById(R.id.html_webview);
		setHtmlWebView(mWebView);
		
		currentdate = StringUtil.getCurrnetDate("yyyy-MM-dd HH:mm:ss");
		sp = PreferenceManager
				.getDefaultSharedPreferences(Splash.this);

		String display_cover = sp.getString("cover", "");
		String display_start = sp.getString("cover_start",
				"1979-01-01 00:00:00");
		String display_end = sp.getString("cover_end", "1979-01-01 00:00:00");

		if (currentdate.compareTo(display_start) >= 0
				&& currentdate.compareTo(display_end) <= 0
				&& !"".equals(display_cover)) {

			try {
				viewstub_ad = (ViewStub) findViewById(R.id.viewstub_ad);
				View vad = viewstub_ad.inflate();
				ImageView adimg = (ImageView) vad.findViewById(R.id.adimg);
				display_cover = PicUtil.getCoverUrl(display_cover, this);
				Bitmap bitmap = PicUtil.readTempJPEGFile(display_cover
						.substring(display_cover.lastIndexOf("/") + 1,
								display_cover.length()));
				adimg.setImageBitmap(bitmap);
				delaymillios = 2000;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				delaymillios = 1000;
			}

		} else {

		}

		// 系统升级或者新安装 需要重新置换新手引导
		int force_count = sp.getInt(FORCE_GUIDE_NAME, -1);
		if (force_count < Constant.FORCE_GUIDE_COUNT) {
			sp.edit().putInt(FORCE_GUIDE_NAME, Constant.FORCE_GUIDE_COUNT)
					.commit();
			sp.edit().putBoolean("newsreaderguide", true).commit();
			sp.edit().putBoolean("detailpageguide", true).commit();
		}
		force_count = sp.getInt(FORCE_TEXTSIZE_NAME, -1);
		if (force_count < Constant.FORCE_TEXTSIZE_COUNT) {
			sp.edit()
					.putInt(FORCE_TEXTSIZE_NAME, Constant.FORCE_TEXTSIZE_COUNT)
					.commit();
			sp.edit().putInt("currentSizeId", 2).commit();
		}

		boolean isAvailable = Tools.CheckNetwork(Splash.this);
		if (isAvailable) {
			new Thread() {
				public void run() {
					try {
						Thread.sleep(1000 * 2);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					handler.sendEmptyMessage(STOP);
				}
			}.start();
		}

		new Thread() {
			public void run() {

				try {


					boolean isAvailable = Tools
							.CheckNetwork(Splash.this);

					Logger.i("network is " + isAvailable);

					if (isAvailable) {

						String result = HttpUtils.getResponseFromGetUrl4GBK(
								StringUtil.NOTICEURL, 2500,
								Splash.this);
						Logger.i("result, ", result);

						JSONObject obj = null;

						obj = new JSONObject(result);

						if (null != obj) {

							// 微新闻监控
							boolean tab_vote = obj.isNull("tab_vote") ? false
									: obj.getBoolean("tab_vote");
							sp.edit().putBoolean("tab_vote", tab_vote).commit();
							// 奥运版切换到正式版
							boolean tab_olympic = obj.isNull("tab_olympic") ? false
									: obj.getBoolean("tab_olympic");
							sp.edit().putBoolean("tab_olympic", tab_olympic)
									.commit();

							version = obj.getString("app_version");
							title = obj.getString("title");
							message = obj.getString("content");
							type = obj.getString("type");
							custom_default = obj.getJSONArray("custom_default");

							String oversion = getResources().getString(
									R.string.versionnum);
							oversion = oversion.substring(1);

							if (null != custom_default
									&& custom_default.length() > 0) {
								JSONObject coverobj = (JSONObject) custom_default
										.get(0);
								cover_src = coverobj.getString("src");

								cover_start = coverobj.getString("start");
								cover_end = coverobj.getString("end");
								handler.sendEmptyMessage(COVER);
							}

							boolean tip_never = sp.getBoolean("tip_never",
									false);

							if (tip_never) { // 选中不在提示选框，检查是否和之前提示的版本一致，如果一致，不提示更新，否则提示更新

								if (UPDATETYPE.equals(type)) {

									String pre_versioin = sp.getString(
											"version", "");

									long nv = 0l;
									long ov = 0l;

									nv = Long.parseLong(version
											.replace(".", ""));
									ov = Long.parseLong(oversion.replace(".",
											""));

									// 选中不再提示选框，要求之前保存的版本和最新获取的版本不同，而且，最新版本号大于软件版本，提示更新，否则不提示
									if (!pre_versioin.equals(version)
											&& nv > ov) {
										handler.sendEmptyMessage(UPDATE);
									} else {
										handler.sendEmptyMessage(NORMAL);
									}
								} else {
									// 选中不再提示选框，要求之前保存的信息和最新获取的版本不同，提示，否则不提示
									String pre_notice = sp.getString("notice",
											"");

									if (!pre_notice.equals(message)) {
										handler.sendEmptyMessage(NOTICE);
									} else {
										handler.sendEmptyMessage(NORMAL);
									}
								}

							} else { // 没有选中不在提示选框，正常检查更新
								if (UPDATETYPE.equals(type)) {

									long nv = 0l;
									long ov = 0l;

									nv = Long.parseLong(version
											.replace(".", ""));
									ov = Long.parseLong(oversion.replace(".",
											""));
									// Log.v("version", "new="+nv+" old="+ov);
									if (nv > ov) {
										handler.sendEmptyMessage(UPDATE);
									} else {
										handler.sendEmptyMessage(NORMAL);
									}
								} else { // 公告
									handler.sendEmptyMessage(NOTICE);
								}
							}

						}
					} else {
						handler.sendEmptyMessage(NORMAL);
					}
				} catch (Exception e) {
					handler.sendEmptyMessage(NORMAL);
					e.printStackTrace();
				}

			}
		}.start();
		
	}

	private Runnable delaystart = new Runnable() {

		@Override
		public void run() {
			if (iscancle) {
				handler.removeCallbacks(delaystart);
			} else {
				Intent i = new Intent(Splash.this, HomePage.class);
				startActivity(i);
				Splash.this.finish();
				VersionCompat.getActivityCompat().overridePendingTransition(
						Splash.this, R.anim.slide_left_in,
						R.anim.slide_left_out);
			}
		}

	};
	
	private void startDelayThread(){
		String path = "file:///android_asset/gethtmlwidth.html";
		mWebView.loadUrl(path);
	}

	private void setHtmlWebView(final WebView webView) {
		webView.clearCache(true);
		webView.setFocusable(false);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		webView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				if(newProgress == 100){
					mWebView.loadUrl("javascript:gethtmlwidth();");
				}
			}
		});
		webView.addJavascriptInterface(new JavaScriptInterface(), "htmltest");
	}

	public class JavaScriptInterface {
		public void setApphtmlwidth(int htmlWidth) {
			sethtmlwidth(htmlWidth);
		}
	}

	private void sethtmlwidth(int htmlwidth) {
		app.mHtmlWidth = htmlwidth;
		handler.postDelayed(delaystart, delaymillios);
	}

	private boolean stopflag = false;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// Log.i("main", "msg.what:"+msg.what +" stopflag:"+stopflag);
			if (stopflag && msg.what != COVER) {
				return;
			}
			switch (msg.what) {
			case STOP:
				stopflag = true;
				startDelayThread();
				break;
			case UPDATE:
				stopflag = true;
				setAlertContext();
				dialog.show();
				break;
			case NOTICE:
				stopflag = true;
				setAlertContext();
				dialog.show();
				break;
			case NORMAL:
				stopflag = true;
				startDelayThread();
				break;
			case COVER:// 下载封面

				new Thread() {

					public void run() {
						String down_cover_src = PicUtil.getCoverUrl(cover_src,
								app);
						Logger.i("down_cover_src:" + down_cover_src);
						if (!PicUtil.isLocalPicExit(down_cover_src.substring(
								down_cover_src.lastIndexOf("/") + 1,
								down_cover_src.length()))) {
							boolean downflag = PicUtil.downloadImgToLocal(
									PicUtil.phototempDir, down_cover_src, app);
							if (downflag) {
								sp.edit().putString("cover", cover_src)
										.commit();
								sp.edit().putString("cover_start", cover_start)
										.commit();
								sp.edit().putString("cover_end", cover_end)
										.commit();
							}

						} else {
							sp.edit().putString("cover", cover_src).commit();
							sp.edit().putString("cover_start", cover_start)
									.commit();
							sp.edit().putString("cover_end", cover_end)
									.commit();
						}
					}
				}.start();

				break;
			}
		}
	};

	private AlertDialog dialog = null;

	private void setAlertContext() {
		if (null == dialog) {
			AlertDialog.Builder b = new AlertDialog.Builder(
					Splash.this);
			dialog = b.create();
			dialog.setIcon(getResources().getDrawable(
					android.R.drawable.ic_dialog_alert));
			dialog.setTitle(title);
			dialog.setMessage(message);
			dialog.setCancelable(false);

			LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			View v = inflater.inflate(R.layout.accountnotice, null);

			dialog.setView(v);

			CheckBox c = (CheckBox) v.findViewById(R.id.n_checkbox);
			Button update = (Button) v.findViewById(R.id.n_udpate);
			Button ok = (Button) v.findViewById(R.id.n_ok);
			Button cancel = (Button) v.findViewById(R.id.n_cancel);

			if ("update".equals(type)) {
				ok.setVisibility(View.GONE);
			} else {
				update.setVisibility(View.GONE);
				cancel.setVisibility(View.GONE);
			}

			c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {

					Editor e = sp.edit();
					e.putBoolean("tip_never", isChecked);
					e.putString("version", version);
					e.putString("notice", message);
					e.commit();

				}
			});

			update.setOnClickListener(new Button.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (null != dialog && dialog.isShowing()) {
						dialog.dismiss();
					}
					// 升级
					Intent intent = new Intent(Splash.this,
							AppUpdateService.class);
					startService(intent);
					
					startDelayThread();
				}
			});

			ok.setOnClickListener(new Button.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (null != dialog && dialog.isShowing()) {
						dialog.dismiss();
					}
					startDelayThread();
				}
			});

			cancel.setOnClickListener(new Button.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (null != dialog && dialog.isShowing()) {
						dialog.dismiss();
					}
					startDelayThread();
				}
			});
		}
	}
}
